using UnityEngine;
using System.Collections.Generic;
using System.Collections;
using System.Diagnostics;
using System;
using Debug = UnityEngine.Debug;
using Random = UnityEngine.Random;
using UnityEngine.SceneManagement;

public class GameManager : MonoBehaviour
{
    private PlayerData player;
    [Header("系统引用")]
    [SerializeField] private MapManager mapManager;
    [SerializeField] private ResultManager resultManager;

    //[SerializeField] private UIManager uiManager;
    [SerializeField] private DataManager dataManager;

    //[SerializeField] private SceneManager sceneManager;

    [Header("测试模式")]
    public bool testMode = true;

    private BattleConfig currentBattleConfig;
    private static GameManager _instance;

    public static GameManager Instance => _instance;

    private void Awake()
    {
        if (_instance == null)
        {
            _instance = this;
            DontDestroyOnLoad(gameObject);
        }
        else
        {
            Destroy(gameObject);
            return;
        }

        // 自动查找依赖
        if (mapManager == null) mapManager = FindObjectOfType<MapManager>();
        if (resultManager == null) resultManager = FindObjectOfType<ResultManager>();
        //if (uiManager == null) uiManager = FindObjectOfType<UIManager>();
        if (dataManager == null) dataManager = FindObjectOfType<DataManager>();
        //if (sceneManager == null) sceneManager = FindObjectOfType<SceneManager>();
        player = FindObjectOfType<PlayerData>();

        Debug.Log("GameManager 初始化完成");
    }

    private void Start()
    {
        if (testMode)
        {
            StartCoroutine(InitializeTestEnvironment());
        }
        else
        {
            // [新增] 非测试模式下，自动开始新游戏，这样地图才会生成！
            Debug.Log("正式模式启动，自动开始新游戏...");
            StartNewGame();
        }
    }

    /// <summary>
    /// 初始化测试环境
    /// </summary>
    private IEnumerator InitializeTestEnvironment()
    {
        Debug.Log("=== 初始化测试环境 ===");

        // 等待一帧确保所有组件初始化完成
        yield return null;

        // 初始化地图系统
        if (mapManager != null)
        {
            mapManager.InitializeNewMap(1);
            Debug.Log("地图系统测试初始化完成");
        }

        Debug.Log("=== 测试环境准备就绪 ===");
        Debug.Log("使用 ContextMenu 进行测试:");
        Debug.Log("1. 测试地图移动");
        Debug.Log("2. 测试战斗胜利结算");
        Debug.Log("3. 测试战斗失败结算");
        Debug.Log("4. 测试完整游戏流程");
    }

    // =========================================================
    // 游戏流程管理
    // =========================================================

    /// <summary>
    /// 开始新游戏
    /// </summary>
    public void StartNewGame()
    {
        Debug.Log("开始新游戏");

        // 重置玩家数据
        dataManager.StartNewGame();

        // 初始化第一幕地图
        mapManager.InitializeNewMap(1);

        // 切换到地图场景（测试模式下跳过）
        if (!testMode)
        {
            //sceneManager.SwitchToScene("MapScene");
        }

        Debug.Log("新游戏初始化完成");
    }

    /// <summary>
    /// 进入战斗
    /// </summary>
    public void EnterBattle(BattleConfig battleConfig)
    {
        currentBattleConfig = battleConfig;
        Debug.Log($"进入战斗: {battleConfig.nodeType}, Boss: {battleConfig.isBossBattle}");

        // 保存战斗配置到静态类
        BattleLoader.battleConfig = battleConfig;
        BattleLoader.playerData = player;

        if (!testMode)
        {
            UnityEngine.SceneManagement.SceneManager.LoadScene("SampleScene");
        }
        else
        {
            // 测试模式下直接模拟战斗
            StartCoroutine(SimulateBattle(battleConfig));
        }
    }

    /// <summary>
    /// 模拟战斗（测试用）
    /// </summary>
    private IEnumerator SimulateBattle(BattleConfig battleConfig)
    {
        Debug.Log("=== 模拟战斗开始 ===");

        // 模拟战斗过程
        yield return new WaitForSeconds(1f);

        // 随机决定胜负（测试用）
        bool isVictory = Random.Range(0, 2) == 1;

        BattleResult result = new BattleResult
        {
            isVictory = isVictory,
            isBossBattle = battleConfig.isBossBattle,
            isEliteBattle = battleConfig.isEliteBattle,
            nodeType = battleConfig.nodeType,
            playerFinalHP = isVictory ? player.currentHP / 2 : 0,
            playerMaxHP = player.maxHP,
            turnsTaken = Random.Range(3, 8),
            goldReward = 25,
            creditReward = battleConfig.nodeType == NodeType.Learning ? 1 : 0,
            nextNodeId = "test_node_2",
            enemyId = battleConfig.enemyIds.Count > 0 ? battleConfig.enemyIds[0] : "test_enemy"
        };

        Debug.Log($"模拟战斗结束: {(isVictory ? "胜利" : "失败")}");

        // 处理战斗结果
        OnBattleFinished(result);
    }

    /// <summary>
    /// 战斗结束回调
    /// </summary>
    public void OnBattleFinished(BattleResult result)
    {
        Debug.Log($"处理战斗结果: {(result.isVictory ? "胜利" : "失败")}");
        resultManager.ProcessBattleResult(result);
    }

    /// <summary>
    /// 返回地图
    /// </summary>
    public void ReturnToMap()
    {
        Debug.Log("返回地图");

        if (!testMode)
        {
            //sceneManager.SwitchToScene("MapScene");
        }
    }

    /// <summary>
    /// 处理游戏结束
    /// </summary>
    public void HandleGameOver()
    {
        Debug.Log("游戏结束");

        // 显示游戏结束界面
        //if (uiManager != null)
        //{
        //    uiManager.ShowMessage("游戏结束！点击开始新游戏重新开始。");
        //}

        // 保存游戏数据
        SaveGame();
    }

    /// <summary>
    /// 处理游戏通关
    /// </summary>
    public void HandleGameCompletion()
    {
        Debug.Log("恭喜通关！");

        //if (uiManager != null)
        //{
        //    uiManager.ShowMessage("恭喜你成功毕业！");
        //}

        // 保存通关记录
        SaveGame();
    }

    /// <summary>
    /// 保存游戏
    /// </summary>
    public void SaveGame()
    {
        Debug.Log("保存游戏数据");
        // todo：实际项目中这里会序列化数据到文件
    }

    /// <summary>
    /// 加载游戏
    /// </summary>
    public void LoadGame()
    {
        Debug.Log("加载游戏数据");
        // todo：实际项目中这里会从文件反序列化数据
    }

    // =========================================================
    // 测试方法
    // =========================================================

    [ContextMenu("测试地图移动")]
    public void TestMapMovement()
    {
        if (mapManager == null)
        {
            Debug.LogError("MapManager 未找到");
            return;
        }

        Debug.Log("=== 测试地图移动 ===");

        // 获取可到达节点
        var reachableNodes = mapManager.GetReachableNodes();
        Debug.Log($"可到达节点数量: {reachableNodes.Count}");

        foreach (var node in reachableNodes)
        {
            Debug.Log($"可到达节点: {node.nodeName} ({node.nodeType})");
        }

        // 移动到第一个可到达节点
        SceneManager.LoadScene("SampleScene");
        if (reachableNodes.Count > 0)
        {
            mapManager.MoveToNode(reachableNodes[0].nodeId);
        }
    }

    [ContextMenu("测试战斗胜利结算")]
    public void TestVictoryResult()
    {
        if (resultManager == null)
        {
            Debug.LogError("ResultManager 未找到");
            return;
        }

        Debug.Log("=== 测试战斗胜利结算 ===");

        BattleResult victoryResult = new BattleResult
        {
            isVictory = true,
            isBossBattle = false,
            isEliteBattle = false,
            nodeType = NodeType.Learning,
            playerFinalHP = 45,
            playerMaxHP = 80,
            turnsTaken = 5,
            goldReward = 30,
            creditReward = 1,
            nextNodeId = "act1_node2",
            enemyId = "test_enemy_1"
        };

        resultManager.ProcessBattleResult(victoryResult);
    }

    [ContextMenu("测试战斗失败结算")]
    public void TestDefeatResult()
    {
        if (resultManager == null)
        {
            Debug.LogError("ResultManager 未找到");
            return;
        }

        Debug.Log("=== 测试战斗失败结算 ===");

        BattleResult defeatResult = new BattleResult
        {
            isVictory = false,
            isBossBattle = false,
            isEliteBattle = false,
            nodeType = NodeType.ChallengeTeacher,
            playerFinalHP = 0,
            playerMaxHP = 80,
            turnsTaken = 8,
            goldReward = 0,
            creditReward = 0,
            nextNodeId = "",
            enemyId = "teacher_enemy"
        };

        resultManager.ProcessBattleResult(defeatResult);
    }

    [ContextMenu("测试完整游戏流程")]
    public void TestFullGameFlow()
    {
        StartCoroutine(RunFullGameFlowTest());
    }

    private IEnumerator RunFullGameFlowTest()
    {
        Debug.Log("=== 开始完整游戏流程测试 ===");

        // 1. 开始新游戏
        StartNewGame();
        yield return new WaitForSeconds(1f);

        // 2. 测试地图移动
        TestMapMovement();
        yield return new WaitForSeconds(1f);

        // 3. 模拟学习节点战斗
        BattleConfig learningBattle = new BattleConfig
        {
            enemyIds = new List<string> { "basic_enemy" },
            isBossBattle = false,
            isEliteBattle = false,
            nodeType = NodeType.Learning
        };

        EnterBattle(learningBattle);
        yield return new WaitForSeconds(2f);

        // 4. 再次移动
        TestMapMovement();
        yield return new WaitForSeconds(1f);

        // 5. 模拟挑战老师节点战斗
        BattleConfig teacherBattle = new BattleConfig
        {
            enemyIds = new List<string> { "teacher_enemy" },
            isBossBattle = false,
            isEliteBattle = true,
            nodeType = NodeType.ChallengeTeacher
        };

        EnterBattle(teacherBattle);
        yield return new WaitForSeconds(2f);

        Debug.Log("=== 完整游戏流程测试完成 ===");
    }

    [ContextMenu("重置测试环境")]
    public void ResetTestEnvironment()
    {
        StopAllCoroutines();
        StartCoroutine(InitializeTestEnvironment());
    }
}